import { useEffect, useRef, useState } from "react"
import { Alert, Image, StyleSheet, Text, TextInput, View } from "react-native"
import UIConstants from "../constants/UIConstants"
import logo from '../assets/img/logo.png'
import AntDesign from '@expo/vector-icons/AntDesign'
import Entypo from '@expo/vector-icons/Entypo'
import ZhButton from "../components/ZhButton"
import userModel from "../viewmodels/UserModel"
import Toast from "react-native-toast-message"
import AsyncStorage from "@react-native-async-storage/async-storage"
import { router } from "expo-router"
export default function ZhUserLogin() {
    let [phone, setPhone] = useState('')
    let [pwd, setPwd] = useState('')
    let [hidePwd, setHidePwd] = useState(true)
    let [phoneError, setPhoneError] = useState('')
    let [pwdError, setPwdError] = useState('')
    let phoneRef = useRef()
    let pwdRef = useRef()

    // 组件加载时，从外部存储中读取保存的手机号和密码
    useEffect(() => {
        AsyncStorage.getItem('LoginPhone').then(p => { setPhone(p) })
        AsyncStorage.getItem('LoginPwd').then(w => { setPwd(w) })
    }, [])

    let doLogin = async () => {
        // 验证手机号
        let regPhone = /^1[3-9]\d{9}$/
        if (!regPhone.test(phone)) {
            Alert.alert(
                '提示',
                '手机号格式错误',
                [
                    { text: '确定' }
                ]
            )
            phoneRef.current.focus()
            return
        }
        // 验证密码
        let len = pwd.length
        if (len < 6 || len > 16) {
            Alert.alert(
                '提示',
                '密码长度6-16位',
                [
                    { text: '确定' }
                ]
            )
            pwdRef.current.focus()
            return
        }
        // 访问服务器端数据API
        let data = await userModel.login(phone, pwd)
        if (data.code === 2000) {
            Toast.show({
                type: 'success',
                text1: '欢迎回来',
                text2: phone,
                visibilityTime: 2000,
                autoHide: true,
            })
            // 在客户端数据库中以键值对形式永久存储登录信息
            await AsyncStorage.setItem('LoginPhone', phone)
            await AsyncStorage.setItem('LoginPwd', pwd)
            router.push('/home')
        } else {
            Toast.show({
                type: 'error',
                text1: '登录失败',
                text2: '手机号或密码错误',
                visibilityTime: 2000,
                autoHide: true,
            })
        }
    }

    return (
        <View>
            {/* --------------------- 顶部图标 ----------------------- */}
            <Image source={logo} style={ss.logo} />


            {/* --------------------- 手机号输入框组 ------------------ */}
            <View style={ss.inputGroup}>
                <AntDesign
                    name="mobile1" size={24}
                    color={UIConstants.COLOR_GREEN}
                />
                <TextInput
                    ref={phoneRef}
                    style={ss.input}
                    placeholder="请输入手机号"
                    keyboardType="phone-pad"
                    maxLength={11}
                    value={phone}
                    onChangeText={value => {
                        const filteredValue = value.replace(/[^\d]/g, '')
                        if (!/^1[3-9]\d{9}$/.test(filteredValue)) {
                            setPhoneError('手机号格式错误')
                        } else {
                            setPhoneError('')
                        }
                        setPhone(filteredValue)
                    }}
                />
                {phone.length > 0 &&
                    <AntDesign
                        name="closecircle" size={20}
                        color={UIConstants.COLOR_BLUE}
                        onPress={() => {
                            setPhone('')
                            setPhoneError('')
                        }}
                    />
                }
            </View>
            {phoneError && <Text style={ss.errorText}>{phoneError}</Text>}


            {/* --------------------- 密码输入框组 -------------------- */}
            <View style={ss.inputGroup}>
                <AntDesign
                    name="lock1" size={24}
                    color={UIConstants.COLOR_GREEN}
                />
                <TextInput
                    ref={pwdRef}
                    style={ss.input}
                    placeholder="请输入密码"
                    secureTextEntry={hidePwd}
                    keyboardType="default"
                    maxLength={16}
                    value={pwd}
                    onChangeText={value => {
                        const filteredValue = value.replace(/[^a-zA-Z0-9_]/g, '')
                        if (value !== filteredValue) {
                            setPwdError('密码只能包含数字、字母、下划线')
                        } else if (filteredValue.length > 0 && filteredValue.length < 6) {
                            setPwdError('密码长度6-16位')
                        } else {
                            setPwdError('')
                        }
                        setPwd(filteredValue)
                    }}
                />
                <Entypo
                    name={hidePwd ? "eye-with-line" : "eye"}
                    size={20}
                    color={UIConstants.COLOR_GRAY}
                    onPress={() => {
                        setHidePwd(!hidePwd)
                    }}
                />
            </View>
            {pwdError && <Text style={ss.errorText}>{pwdError}</Text>}


            {/* --------------------- 登录按钮 ------------------------ */}
            <View style={ss.btnBox}>
                <ZhButton
                    title="登 录"
                    bgColor={UIConstants.COLOR_GREEN}
                    onPress={() => { doLogin() }}
                />
            </View>
            {/* --------------------- 忘记密码链接 --------------------- */}
        </View>
    )
}

let ss = StyleSheet.create({
    logo: {
        marginHorizontal: 'auto',
        marginTop: UIConstants.SPACE_COL_XL * 5,
    },
    inputGroup: {
        backgroundColor: '#F8F8F8',
        width: '90%',
        marginHorizontal: 'auto',
        marginTop: UIConstants.SPACE_COL_XL * 2,
        borderRadius: UIConstants.BORDER_RADIUS_MD,
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: UIConstants.SPACE_ROW_LG
    }
    ,
    input: {
        flex: 1,
    },
    btnBox: {
        width: '40%',
        marginHorizontal: 'auto',
        marginTop: UIConstants.SPACE_COL_XL * 4,
    },
    errorText: {
        width: '80%',
        color: UIConstants.COLOR_RED,
        fontSize: 14,
        marginTop: UIConstants.SPACE_COL_SM,
        marginHorizontal: 'auto',
    }
})